package com.ai.main.controller;

import com.ai.main.repository.ChatHistoryRepository;
import com.ai.main.vo.MessageVO;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.List;

/**
 * 功能描述
 *
 * @author: jichao.huang
 * @date: 2025年06月04日 21:49
 */
@RequiredArgsConstructor
@RequestMapping("/api/history")
@RestController
public class ChatHistoryController {
    private final ChatClient chatClient;

    private final ChatHistoryRepository chatHistoryRepository;

    private final ChatMemory chatMemory;

    @GetMapping(value = "/stream", produces = "text/html;charset=utf-8")
    public Flux<String> chatMemory(String prompt, String chatId) {
        chatHistoryRepository.save("chat", chatId);

        return this.chatClient
                .prompt(prompt)
                .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, chatId))
                .stream()
                .content();
    }

    @GetMapping(value = "/{type}")
    public List<String> getChatIds(@PathVariable String type) {
        return chatHistoryRepository.getChatIds(type);
    }

    @GetMapping(value = "/{type}/{chatId}")
    public List<MessageVO> getChatIds(@PathVariable String type, @PathVariable String chatId) {
        final List<Message> messages = chatMemory.get(chatId);
        //return messages.stream().map(item->new MessageVO(item)).toList();
        return  messages.stream().map(MessageVO::new).toList();
    }
}
